//index.js
//获取应用实例
const app = getApp();
let utils = require('../../utils/util.js');

Page({
  data: {
    hadInit: false,       //是否初始化过
    cellLoading: false,       //是否正在加载cell信息
    allItemsLoaded: true,
    scrollHeight: 0,        //"滚动视图的高度"
    pageNum: 6,         //每页多少条商品数据
    orderItems: [],
    showEmpty: false,
    intervalId: -1000,           //刷新现成团计时器id
    pollInterval: 5,            //轮询间隔的时间
    pollConut: 0,               //轮询计时
    firOrderNo: '',            //最后请求的订单数量
    exitArr: [],         //已经加载过的订单id
    dialog:null
  },
  requestData(fisrtLoad = false) {
    let requestObj;
    if (this.data.firOrderNo === '') {
      requestObj = { pageSize: this.data.pageNum };
    } else requestObj = { firOrderNo: this.data.firOrderNo, pageSize: this.data.pageNum }
    app.post('user/order/list', requestObj, this, this.requestData, [true]).then((res) => {
      if (!this.data.hadInit) this.data.hadInit = true;
      let serverItems = this.transformData(res.data.data);
      let orderItems = this.data.orderItems;
      if (!serverItems || serverItems.length < this.data.pageNum) {    //没有满一页
        this.setData({ cellLoading: true });
        if (serverItems && serverItems.length !== 0) {                          //没有满一页但是有数据
          this.pushItems(orderItems, serverItems);
          this.data.firOrderNo = serverItems[serverItems.length - 1].orderId;
          this.setData({ "orderItems": orderItems, allItemsLoaded: true });
        } else {
          if (fisrtLoad) this.setData({ allItemsLoaded: true, "showEmpty": true });
          else this.setData({ allItemsLoaded: true });
        }
      }
      else {  //满一页
        this.setData({ cellLoading: false });
        this.data.firOrderNo = serverItems[serverItems.length - 1].orderId;
        this.pushItems(orderItems, serverItems);
        this.setData({ "orderItems": orderItems });
      }
    }).catch((errMsg) => {
      console.log(errMsg);    //错误提示信息
    });
  },
  pushItems(orderItems, serverItems) {      //向当前的列表添加订单数据
    for (let i = 0; i < serverItems.length; i++) {
      let serverItem = serverItems[i];
      if (this.data.exitArr.indexOf(serverItem.orderId) >= 0) continue;
      orderItems.push(serverItem);
      this.data.exitArr.push(serverItem.orderId);
    }
  },
  transformData(serverList) {
    if (!serverList || serverList.length === 0) return serverList;
    let tempArr = [];
    for (let i = 0; i < serverList.length; i++) {
      let serverItem = serverList[i];
      let item = {
        id: serverItem.id,
        groupId: serverItem.groupId,
        orderId: serverItem.orderNo,
        groupNo: serverItem.groupNo,
        itemName: serverItem.itemName,
        itemNum: serverItem.itemQuantity,
        groupPrice: serverItem.itemPrice,
        buyTime: utils.formatTime(new Date(parseInt(serverItem.createTime))),
        state: serverItem.status,
        stateWords: this.getStateWords(serverItem.status)
      };
      tempArr.push(item);
    }
    return tempArr;
  },
  //下拉刷新
  onPullDownRefresh() {
    //模拟加载
    let clearId = setTimeout(() => {
      clearTimeout(clearId);
      wx.stopPullDownRefresh();        //停止下拉刷新
    }, 800);
  },
  //加载更多
  onReachBottom() {
    console.log("触发加载更多....");
    if (this.data.showEmpty) return;
    if (this.data.cellLoading) return;
    this.setData({ cellLoading: true });
    utils.throttle(this.loadMore, 600, 300)();
  },
  loadMore() {
    this.requestData(false);
  },
  onLoad() {
    //获取滚动条的高度
    wx.getSystemInfo({
      success: res => {
        this.setData({ scrollHeight: res.windowHeight });
      }
    });
  },
  initData(delayInit){
    this.setData({ allItemsLoaded: false, "showEmpty": false });
    if (delayInit){
      let delayId = setTimeout(() => {
        clearTimeout(delayId);
        this.requestData(true);
      }, 400);
    }else{
      this.requestData(true);
    }
  },
  checkAddNewOrder(){
    //如果有新的订单，做一个假的loading，并刷新数据
    if (app.globalData.newOrders.length > 0) {
      wx.showLoading({ mask: true, title: '请稍后' });
      let clearId = setTimeout(() => {
        wx.hideLoading();
      }, 650);
      //检测是否已经包含了改订单，若为新订单从头部添加进去，
      for (let i = 0; i < app.globalData.newOrders.length; i++) {
        let newOrder = app.globalData.newOrders[i];
        //发现了新的订单;
        if (this.data.exitArr.indexOf(newOrder.orderId) >= 0) continue;
        this.data.orderItems.unshift(newOrder);
        this.data.exitArr.push(newOrder.orderId);
      }
      app.globalData.newOrders = [];
      //当前如果是空订单状态，取消空订单状态
      if (this.data.showEmpty) {
        this.setData({ "showEmpty": false }, () => {
          this.refreshOrdersState();
        });
      } else {
        this.refreshOrdersState();
      }
    } else {
      this.refreshOrdersState();
    }
  },
  onShow() {
    this.data.pollConut = 0;
    this.addInterval();
    //如果没有加载过数据，去加载第一批数据
    if (!this.data.hadInit) {
      if (app.globalData.authorization) {
        if (this.data.dialog){
          this.data.dialog.hideDialog();
          this.data.dialog = null;
        }
        this.initData(true);
      } else if (!this.data.dialog){
        this.data.dialog = this.selectComponent("#dialog");
        wx.getSetting({
          success: res => {
            if (!res.authSetting['scope.userInfo']) {     //未授权
              this.data.dialog.showDialog();
              this.setData({"showEmpty": true });
            } else {
              app.globalData.authorization = true;
            }
          }
        });
      }
    } else this.checkAddNewOrder();
  },
  //弹出框确认事件
  _confirmEvent() {
    app.globalData.authorization = true;
    this.data.dialog.hideDialog();
    this.data.dialog = null;
    this.initData(false);
  },
  myCatchTouch() {

  },
  onHide() {
    this.removeInterval();
  },
  addInterval() {                           //添加计时器
    if (this.data.intervalId !== -1000) return;
    this.data.pollConut = 0;
    this.data.intervalId = setInterval(this.intervalHandle, 1000);
  },
  intervalHandle() {                        //计时器处理
    if (!this.data.hadInit) return;
    this.data.pollConut++;
    if (this.data.pollConut >= this.data.pollInterval) {
      this.data.pollConut = 0;
      this.refreshOrdersState();
    }
  },
  removeInterval() {                     //移除计时器
    if (this.data.intervalId === -1000) return;
    clearInterval(this.data.intervalId);
    this.data.intervalId = -1000;
  },
  refreshOrdersState() {
    app.post('user/order/list', {
      pageSize: 100
    }).then((res) => {
      let serverItems = res.data.data;
      if (!serverItems || serverItems.length === 0) return;
      let orderItems = this.data.orderItems;
      let hasChange = false;
      for (let i = 0; i < orderItems.length; i++) {
        let serverItem = serverItems[i];
        let item = this.data.orderItems[i];
        if (item.orderId !== serverItem.orderNo) continue;
        if (item.state === serverItem.status) continue;
        item.id = serverItem.id;
        item.groupId = serverItem.groupId;
        item.groupNo = serverItem.groupNo;
        item.itemName = serverItem.itemName;
        item.itemNum = serverItem.itemQuantity;
        item.groupPrice = serverItem.itemPrice;
        item.buyTime = utils.formatTime(new Date(parseInt(serverItem.createTime)));
        item.state = serverItem.status;
        item.stateWords = this.getStateWords(serverItem.status);
        hasChange = true;
      }
      if (hasChange) {
        this.setData({ 'orderItems': orderItems });
        console.log('更新了订单数据');
      }
    }).catch((errMsg) => {
      console.log(errMsg);    //错误提示信息
    });
  },
  getStateWords(state) {
    if (state.toString() === '1') return '未支付';
    if (state.toString() === '2') return '进行中';
    else if (state.toString() === '3') return '退款中';
    else if (state.toString() === '4') return '已退款';           //退款中
    else if (state.toString() === '5') return '已成功';
  },
  lookDetails(e) {       //点击开团按钮事件处理
    console.log("e.currentTarget.dataset.orderid=" + e.currentTarget.dataset.groupno);
    let groupNo = e.currentTarget.dataset.groupno
    wx.navigateTo({
      url: `../join/join?id=${groupNo}`
    })
  }
})

